package com.mh.zookeeper.api;

import org.apache.zookeeper.*;

import java.io.IOException;

import static com.mh.zookeeper.PropertiesUtils.getZookeeperConnectStr;

/**
 * @author MH
 * @since 2021-12-21
 */
public class CreateNode implements Watcher {

    private static ZooKeeper zooKeeper;

    public static void main(String[] args) throws IOException, InterruptedException {
        zooKeeper = new ZooKeeper(getZookeeperConnectStr(), 5000, new CreateNode());
        System.out.println(zooKeeper.getState());

        Thread.sleep(Integer.MAX_VALUE);
    }

    @Override
    public void process(WatchedEvent watchedEvent) {
        if (watchedEvent.getState() == Event.KeeperState.SyncConnected) {
            System.out.println("process方法执行了 ...");
            try {
                createNodeSync();
            } catch (InterruptedException | KeeperException e) {
                e.printStackTrace();
            }
        }
    }

    private void createNodeSync() throws InterruptedException, KeeperException {
        String nodePersistent = zooKeeper.create("/lg-persistent",
                "持久节点内容".getBytes(),
                ZooDefs.Ids.OPEN_ACL_UNSAFE,
                CreateMode.PERSISTENT);

        String nodeEphemeral = zooKeeper.create("/lg-ephemeral",
                "临时节点内容".getBytes(),
                ZooDefs.Ids.OPEN_ACL_UNSAFE,
                CreateMode.EPHEMERAL);

        String nodePersistentSequential = zooKeeper.create("/lg-persistent-sequential",
                "持久顺序节点内容".getBytes(),
                ZooDefs.Ids.OPEN_ACL_UNSAFE,
                CreateMode.PERSISTENT_SEQUENTIAL);

        System.out.println("创建的持久节点：" + nodePersistent);
        System.out.println("创建的临时节点" + nodeEphemeral);
        System.out.println("创建的持久顺序节点" + nodePersistentSequential);

    }
}
